Yo uso el paquete simple-git . tengo la siguiente función:
import simpleGit from 'simple-git'; /** * The function returns the ticket Id, is presents, in the branch name * @returns ticket Id */ export const getTicketIdFromBranchName = async (ticketRegex: RegExp) => { const git = simpleGit(); try { const localBranches = await git.branchLocal(); const currentBranch = localBranches.current; const currentBranchTicketMatches = currentBranch.match(ticketRegex); if (currentBranchTicketMatches) { return currentBranchTicketMatches[0]; } return null; } catch { return null; } };Intento crear una prueba unitaria para esta función:
import { getTicketIdFromBranchName } from '@/utils/git-info'; const TICKET_ID_REGEX = /((?<!([AZ]{1,10})-?)[AZ]+-\d+)/.source; describe('[utils/git-info]', () => { it('getTicketIdFromBranchName | Function should proper ticket Id when there is one', async () => { const ticketId = 'CLO-1234'; jest.mock('simple-git', () => { const mGit = { branchLocal: jest.fn(() => Promise.resolve({ current: `${ticketId} DUMMY TEST` })), }; return jest.fn(() => mGit); }); const result = await getTicketIdFromBranchName(new RegExp(TICKET_ID_REGEX)); expect(result === ticketId).toEqual(true); }); }); Pero la prueba unitaria falla. Digo que esperaba que se volviera true , pero se volvió false en la línea final.
Supongo que uso jest.mock de manera incorrecta.
La documentación oficial tiene una descripción clave del uso de jest.mock .
Nota: para simular correctamente, Jest necesita
jest.mock('moduleName')esté en el mismo ámbito que la instrucciónrequire/import.
Llamas a jest.mock('moduleName') dentro del alcance de la función del caso de prueba, pero import el módulo git-info en el alcance del módulo. Es por eso que la simulación no funciona.
Use require('moduleName') o await import('moduleName') en la función de caso de prueba. El orden de las instrucciones require/import y jest.mock() no importa.
git-info.js :
import simpleGit from 'simple-git'; /** * The function returns the ticket Id, is presents, in the branch name * @returns ticket Id */ export const getTicketIdFromBranchName = async (ticketRegex) => { const git = simpleGit(); try { const localBranches = await git.branchLocal(); const currentBranch = localBranches.current; const currentBranchTicketMatches = currentBranch.match(ticketRegex); if (currentBranchTicketMatches) { return currentBranchTicketMatches[0]; } return null; } catch { return null; } }; git-info.test.js :
const TICKET_ID_REGEX = /((?<!([AZ]{1,10})-?)[AZ]+-\d+)/.source; describe('[utils/git-info]', () => { it('getTicketIdFromBranchName | Function should proper ticket Id when there is one', async () => { const { getTicketIdFromBranchName } = await import('./git-info'); const ticketId = 'CLO-1234'; jest.mock( 'simple-git', () => { const mGit = { branchLocal: jest.fn(() => Promise.resolve({ current: `${ticketId} DUMMY TEST` })), }; return jest.fn(() => mGit); }, { virtual: true } ); const result = await getTicketIdFromBranchName(new RegExp(TICKET_ID_REGEX)); expect(result === ticketId).toEqual(true); }); });Resultado de la prueba:
PASS stackoverflow/71808909/git-info.test.js (7.439 s) [utils/git-info] ✓ getTicketIdFromBranchName | Function should proper ticket Id when there is one (6892 ms) -------------|---------|----------|---------|---------|------------------- File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s -------------|---------|----------|---------|---------|------------------- All files | 84.62 | 50 | 100 | 81.82 | git-info.js | 84.62 | 50 | 100 | 81.82 | 19-21 -------------|---------|----------|---------|---------|------------------- Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 8.215 s, estimated 9 s versión del paquete: "jest": "^26.6.3"